package com.example.shushiyunsst.fragment.main.wallet.sub

import android.os.Bundle
import android.text.Editable
import android.view.View
import androidx.appcompat.widget.Toolbar
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import com.alibaba.fastjson.JSON
import com.example.library_common.base.BaseDataBindingFragment
import com.example.library_common.base.BaseFragmentEx
import com.example.library_common.networking.RestClient
import com.example.library_common.utils.OnTextListener
import com.example.library_common.utils.normalShortToast
import com.example.shushiyunsst.R
import com.example.shushiyunsst.databinding.PassCardExchangeFragmentBinding
import com.example.shushiyunsst.fragment.getUserBalanceInfo
import com.example.shushiyunsst.fragment.main.wallet.bean.WalletHeadBean
import com.example.shushiyunsst.scan.ScanFrameFragment
import com.example.shushiyunsst.scan.ScanResListener
import com.example.shushiyunsst.util.extension.goneAlphaAnimation
import com.example.shushiyunsst.util.extension.visibleAlphaAnimation
import com.example.wallet.bean.BalanceInfoBean
import com.example.wallet.db.UserInfoManager
import com.lxj.xpopup.XPopup
import com.lxj.xpopup.core.BottomPopupView
import com.senon.modularapp.util.JssSpannableString
import kotlinx.android.synthetic.main.ping_tuan_fragment.view.*

class PassCardExchangeFragment : BaseDataBindingFragment<PassCardExchangeFragmentBinding>(),
    View.OnClickListener, OnTextListener {

    companion object {
        fun newInstance(item: BalanceInfoBean.ListBean): PassCardExchangeFragment {
            val args = Bundle()
            args.putSerializable("item", item)
            val fragment = PassCardExchangeFragment()
            fragment.arguments = args
            return fragment
        }
    }

    private var item: BalanceInfoBean.ListBean? = null

    private val step = 100

    private var currentCount = 0

    private var lastNum = ""

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        item = arguments?.getSerializable("item") as BalanceInfoBean.ListBean
    }

    override fun layoutId(): Int {
        return R.layout.pass_card_exchange_fragment
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        val mToolbar: Toolbar = view.findViewById(R.id.mToolbar)
        mToolbar.title = _mActivity.getString(R.string.mExchangePass)
        mToolbar.setNavigationOnClickListener { onBackPressedSupport() }

        viewBinder.item = item
        viewBinder.onViewClick = this
        viewBinder.onTextListener = this
        val walletHeadBean = WalletHeadBean(item?.balance, item?.balanceCny, item?.tokenType)
        loadRootFragment(R.id.wallet_header, WalletHeadFragment.newInstance(walletHeadBean))

//        setNum()
        val suffix = "(使用本人地址)"

        val userInfo = UserInfoManager.userInfoManager.getUserInfoWrapper()?.userInfo
        viewBinder.addressTv.setText("${userInfo?.sysWalletAddress}")

        viewBinder.addressTitle.text = JssSpannableString(_mActivity, "接收地址 $suffix")
            .first(suffix)
            .scaleSize(0.8f)
            .onClick(viewBinder.addressTitle, R.color.PrimaryColor) {
                val userInfo = UserInfoManager.userInfoManager.getUserInfoWrapper()?.userInfo
                viewBinder.addressTv.setText("${userInfo?.sysWalletAddress}")
            }

        viewBinder.mTokenType.text = _mActivity.getString(R.string.wallet_cml)

    }

    private fun setNum() {
        currentCount = if (currentCount < 0) 0 else currentCount
//        viewBinder.priceEtv.text = "${currentCount * step}"
        val txNums = viewBinder.muBi.text.toString().trim()

        RestClient.builder()
            .url(R.string.exchangeYSAlgorithm)
            .raw(
                JSON.toJSONString(
                    mapOf(
//                        "txNums" to currentCount * step
                        "txNums" to txNums
                    )
                )
            ).success {
                val obj = JSON.parseObject(it)
                val content = obj["content"].toString()
                val pop = XPopup.Builder(_mActivity)
                    .asConfirm("说明", content) {
                        sending()
                    }

                pop.cancelTextView.text = "取消"
                pop.confirmTextView.text = "确定"

                pop.show()
//                XPopup.Builder(_mActivity)
//                    .asConfirm("说明",content){
//                        sending()
//                    }
//                    .show()

//                viewBinder.feedingTv.text = content
//                if (currentCount > 0) {
//                    viewBinder.feedingLayout.visibleAlphaAnimation()
//                } else {
//                    viewBinder.feedingLayout.goneAlphaAnimation()
//                }

            }
            .error { _, msg ->
                normalShortToast(_mActivity, msg)
            }
            .failure {
                normalShortToast(_mActivity, R.string.net_work_failed)
            }
            .build().post()
    }

    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.countTv -> {

                currentCount++

                setNum()

                viewBinder.sureTv.isSelected = checkInfo(false)
            }
            R.id.discount -> {
                if (currentCount < 0) return
                currentCount--
                setNum()
                viewBinder.sureTv.isSelected = checkInfo(false)
            }

            R.id.mSaner -> {
                val newInstance = ScanFrameFragment.newInstance()
                newInstance.setScanResListener(object : ScanResListener {
                    override fun onResStr(resStr: String) {
                        viewBinder.addressTv.setText(resStr)
                    }
                })
                start(newInstance)

            }

            R.id.sureTv -> {
                if (!checkInfo(true)) {
                    return
                }
                showPop()
//                sending()
            }
        }
    }

    private fun showPop() {
        setNum()


    }

    private fun sending() {
        val addressTvStr = viewBinder.addressTv.text.toString()
        val txNums = viewBinder.muBi.text.toString()
        RestClient.builder()
            .url(R.string.exchangeYS)
            .raw(
                JSON.toJSONString(
                    mapOf(
                        "addr" to addressTvStr,
//                        "txNums" to currentCount * step
                        "txNums" to txNums.toLong()
                    )
                )
            ).success {
                normalShortToast(_mActivity, R.string.operate_succeed)
                getUserBalanceInfo(_mActivity)
                onBackPressedSupport()

            }
            .error { _, msg ->
                normalShortToast(_mActivity, msg)
            }
            .failure {
                normalShortToast(_mActivity, R.string.net_work_failed)
            }
            .build().post()
    }

    override fun afterTextChanged(s: Editable?, viewId: Int) {
        when (viewId) {
            R.id.addressTv -> {
                viewBinder.sureTv.isSelected = checkInfo(false)

            }
            R.id.mu_bi -> {

//                lastNum = s.toString()
                viewBinder.sureTv.isSelected = checkInfo(false)

//                viewBinder.sureTv.text="获取兑换"
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        hideSoftInput()
    }

    private fun checkInfo(showMsg: Boolean): Boolean {
        var flag = true
        val addressTvStr = viewBinder.addressTv.text.toString()
        if (addressTvStr.isEmpty()) {
            if (showMsg) {
                normalShortToast(_mActivity, "接收地址不能为空")
            }

            flag = false
        }

        val txNums = viewBinder.muBi.text.toString()

        if (txNums.isEmpty()) {
            if (showMsg) {
                normalShortToast(_mActivity, "兑换数量不能为空")
            }
            flag = false
        }

//        if (currentCount<=0){
//            if (showMsg){
//                normalShortToast(_mActivity,"兑换数量不能为0")
//            }
//            flag=false
//        }
        return flag
    }


}